/**
 * 
 * 起迪科技 Copyright (c) 2014-2018 QiDi,Inc.All Rights Reserved.
 */
package cn.qidisoft.edu.hzjt.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.moffice.excel.ErrorMessageBean;
import cn.qidisoft.core.util.moffice.excel.ExcelUtil;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.core.util.moffice.excel.ImportMsgHelper;
import cn.qidisoft.core.web.customargument.bind.annotation.IfNeedLogin;
import cn.qidisoft.core.web.customargument.bind.annotation.Token;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.StudentDemo;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.service.IStudentDemoService;
import cn.qidisoft.edu.hzjt.utils.LogType;

/**
 * 
 * @author hxq
 * @version $Id: demoController.java, v 0.1 2018年10月22日 下午5:28:26 hxq Exp $
 */
@Controller
@RequestMapping("demo")
@IfNeedLogin(needLogin = true)
public class demoController {
  protected static final LoggerAdapter LOGGER =
      LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);
  @Autowired
  private IStudentDemoService studentDemoService;

  @RequestMapping(value = "/indexDemo")
  public String indexDemo(ModelMap model, HttpServletRequest request) {
    try {
    } catch (Exception e) {
      LOGGER.error("获得xxxxx信息 indexDemo [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return "demo/displayList";
  }

  /**
   * 查询列表
   * 
   * @param model
   * @param request
   * @param pageSize
   * @param currentPage
   * @param fd
   * @return
   */
  @RequestMapping(value = "/demoList")
  @ResponseBody
  public ResponseResult demoList(ModelMap model, HttpServletRequest request,
      @RequestParam(value = "rows", required = false) String pageSize,
      @RequestParam(value = "page", required = false) String currentPage, StudentDemo student) {
    try {
      Page page = new Page();
      page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
      page.setPageSize(pageSize == null ? 10 : Integer.valueOf(pageSize));
      BaseController.setSortByColumn(request, "name", "asc");
      student.setOrderField((String) request.getAttribute("orderField"));
      student.setOrderFlag((String) request.getAttribute("orderFlag"));
      PaginationBean<StudentDemo> paginationBean =
          studentDemoService.queryStudentDemoPageList(student, page);
      ResponseResult result = new ResponseResult();
      result.setTotal(paginationBean.getTotalRecords());
      result.setRows(paginationBean.getPageList());
      return result;
      //
      // model.addAttribute("list", paginationBean.getPageList());
      // model.addAttribute("listPage", paginationBean);
      // model.addAttribute("name", student.getName());
      // request.setAttribute("msg", BaseController.getParameter("msg"));
      // BaseController.removeParameter("msg");

    } catch (Exception e) {
      LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());

    }
    return null;
  }

  /**
   * xxxx新增页面跳转
   * 
   * @param model
   * @param request
   * @return
   */
  @RequestMapping(value = "/addStudentDemoForward")
  @Token(save = true)
  public String addStudentDemoForward(ModelMap model, HttpServletRequest request) {
    try {

    } catch (Exception e) {
      LOGGER.error(
          "获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return "demo/addDemo";
  }

  /**
   * xxxxx保存功能
   * 
   * @param model
   * @param request
   * @return
   */
  @RequestMapping(value = "/addStudentDemo")
  @Token(remove = true, path = "indexDemo")
  @SysLogger(description = "描述功能做什么的", moduleName = "模块名称", method = "描述访问的方法：比如：新增、修改等")
  public String addStudentDemo(ModelMap model, HttpServletRequest request) {
    UserEmployee userResp =
        (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
    try {

    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return "redirect:indexDemo";
  }

  /**
   * xxxx修改功能跳转页面
   * 
   * @param model
   * @param request
   * @return
   */
  @RequestMapping(value = "/modfityStudentDemoForward")
  public String modfityStudentDemoForward(ModelMap model, HttpServletRequest request) {
    try {
      // 写具体处理业务信息
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error(
          "获得xxxxx信息 modfityStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return "demo/editDemo";
  }

  /**
   * xxxxx修改功能
   * 
   * @param model
   * @param request
   * @return
   */
  @RequestMapping(value = "/modfityStudentDemo")
  @SysLogger(description = "描述功能做什么的", moduleName = "模块名称", method = "描述访问的方法：比如：新增、修改等")
  public String modfityStudentDemo(ModelMap model, HttpServletRequest request) {
    UserEmployee userResp =
        (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
    try {

    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("获得xxxxx信息 modfityStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return "demo/editDemo";
  }

  /**
   * 
   * xxx导入功能信息
   * 
   * @param multipartFile
   * @param model
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importStudentDemo", method = RequestMethod.POST)
  @SysLogger(description = "描述功能做什么的", moduleName = "模块名称", method = "描述访问的方法：比如：新增、修改等")
  public String importStudentDemo(MultipartFile multipartFile, ModelMap model,
      HttpServletRequest request, HttpServletResponse response) {
    UserEmployee userResp =
        (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
    List<ErrorMessageBean> errorList = new ArrayList<ErrorMessageBean>(); // 创建错误集合对象
    try {
      // MultipartFile file = practiceMasterForm.getFormfile();
      if (multipartFile != null) {
        String name = multipartFile.getOriginalFilename();// 获取上传文件名,包括路径
        InputStream in = multipartFile.getInputStream(); // 获取文件对象
        HSSFWorkbook wb = null; // 创建工作簿
        HSSFSheet sheet = null; // 创建工作sheet
        try {
          wb = ExcelUtil.getWorkbook(in); // 检查Excel格式和路径是否有效
          sheet = ExcelUtil.getFirstSheet(wb);
          if (sheet == null) {
            ImportMsgHelper.addErrorList(errorList, "sys-error", ImportMsgHelper.msg_validate_1001);
            // return errorList;
          } else {
            String[] header = ExcelUtil.getFirstSheetRow(sheet); // 得到excel表头
            int totalRows = sheet.getPhysicalNumberOfRows(); // totalRows是总行数
            long startTime = System.nanoTime();
            String exportFlag = request.getParameter("exportFlag");
            errorList = studentDemoService.importStudentDemo(errorList, wb, sheet, header,
                totalRows, in, Integer.parseInt(exportFlag));
            long estimatedTime = (long) ((System.nanoTime() - startTime) * 0.000000001);
            if (errorList.size() > 0 && totalRows <= 1) {
              model.addAttribute("flag", Constant.ALL_FAIL);// 失败
            } else if (errorList.size() > 0 && errorList.size() < totalRows - 1) {
              model.addAttribute("flag", Constant.PART_SUCESS);// 部分成功
            } else if (errorList.size() == 0) {
              model.addAttribute("flag", Constant.All_SUCESS);// 全部成功
            } else if (errorList.size() == totalRows - 1) {
              model.addAttribute("flag", Constant.ALL_FAIL);// 失败
            }
            model.addAttribute("estimatedTime", estimatedTime);
            model.addAttribute("Count", totalRows - 1);
            model.addAttribute("sucessCout", totalRows - errorList.size() - 1);
            model.addAttribute("failCout", errorList.size());
          }
        } catch (Exception e) {
          ImportMsgHelper.addErrorList(errorList, "sys-error", ImportMsgHelper.msg_validate_0001);
          e.printStackTrace();
          // return errorList;
        }
      }
      model.addAttribute("errorList", errorList);
      model.addAttribute("now", new Date());
      model.addAttribute("project", "xxxx信息导入");
      model.addAttribute("backUrl", "demo/indexDemo");
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("获得xxxxx信息 importStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return "import_message";
  }

  /**
   * xxxxx下载
   * 
   * @param form
   * @param request
   * @param response
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "/exportStudentDemo")
  public @ResponseBody String exportStudentjobList(HttpServletRequest request,
      HttpServletResponse response, StudentDemo student, ModelMap model) throws Exception {
    UserEmployee userResp =
        (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
    try {
      Page page = new Page();
      page.setCurrPage(0);
      page.setPageSize(15);
      BaseController.setSortByColumn(request, "name", "asc");
      student.setOrderField((String) request.getAttribute("orderField"));
      student.setOrderFlag((String) request.getAttribute("orderFlag"));
      PaginationBean<StudentDemo> paginationBean =
          studentDemoService.queryStudentDemoPageList(student, page);
      ResponseResult result = new ResponseResult();
      result.setTotal(paginationBean.getTotalRecords());
      result.setRows(paginationBean.getPageList());

      String[][] title_name = {{"姓名", "年龄", "成绩"}};
      String[] title_style = {"hwzs_16_bold_25", "kt_12_bold_18", "st_12_r_20", "st_12_n_20"};
      String fileName = "xxxx信息";
      String[] remark = {""};
      List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
      if (paginationBean.getPageList() != null && !paginationBean.getPageList().isEmpty()) {
        for (StudentDemo res : paginationBean.getPageList()) {
          Map<String, Object> map = new LinkedHashMap<String, Object>();
          map.put("name", res.getName());
          map.put("age", res.getAge());
          map.put("score", res.getScore());
          list.add(map);
        }
      }
      HSSFWorkbook wb =
          ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, list);

      try {

        String filenameConvert =
            "xxxxx信息";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="
            + new String((filenameConvert + ".xls").getBytes(), "iso-8859-1"));
        response.setDateHeader("Expires", 0);
        ServletOutputStream os = response.getOutputStream();
        wb.write(os);
        os.flush();
      } catch (Exception e) {
        System.out.println("网络连接断开，可能用户取消了导出");
        model.addAttribute(Constant.EXPTION_MSG_KEY, e);
        return "error/error";
      }
    } catch (RPCException e) {
      LOGGER.error(
          "获得xxxxx信息 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return null;
  }

}
